package ru.niir.goodfil.audit.util;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class PropertyHistoryPrinter {
    private final Map<Class, Converter> customConverters = new LinkedHashMap<Class, Converter>();

    private void addCustomConverter(Class klass, Converter converter) {
        Assert.notNull(klass);
        Assert.notNull(converter);

        customConverters.put(klass, converter);
    }


    private String getAsString(Object o) {
        if (o == null) {
            return String.valueOf(o);
        } else {
            Class klass = o.getClass();
            if (customConverters.containsKey(klass)) {
                Converter converter = customConverters.get(klass);
                return converter.getAsString(o);
            } else {
                return String.valueOf(o);
            }
        }
    }

    public StringablePropertyHistoriesList getStringablePropertyHistoriesList(List<PropertyHistory> items) {
        List<StringablePropertyHistory> result = new ArrayList<StringablePropertyHistory>();

        for (PropertyHistory propertyHistory : items) {
            StringablePropertyHistory str = new StringablePropertyHistory();
            str.setPropertyName(propertyHistory.getPropertyName());
            str.setOldValue(getAsString(propertyHistory.getOldValue()));
            str.setNewValue(getAsString(propertyHistory.getNewValue()));
            result.add(str);
        }

        return new StringablePropertyHistoriesList(result);
    }

    public static interface Converter {
        String getAsString(Object o);
    }
}
